package com.tgb.lk.ui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.*;

import com.tgb.lk.autossh.AutoMain;
import com.tgb.lk.autossh.DBExcelDataUtil;
import com.tgb.lk.config.Config;
import com.tgb.lk.config.ConfigXmlUtil;
import com.tgb.lk.table.Log;
import com.tgb.lk.table.TableConfig;
import com.tgb.lk.util.AppConstants;
import com.tgb.lk.util.FileUtil;

public class Main extends JFrame implements ActionListener, Runnable {
	private static final long serialVersionUID = 1L;
	private JMenuBar menuBar;
	private JMenu menuFile;
	private JMenu menuEdit;
	private JMenu menuHelp;
	private JMenuItem miStart;
	private JMenuItem miDoc;
	private JMenuItem miCompileJava;
	private JMenuItem miAutoSSH;
	private JMenuItem miAutoConfig;
	private JMenuItem miConfig;
	private JMenuItem miSelectTable;
	private JMenuItem miAbout;
	private BorderLayout borderLayout;
	private JTextArea taInfo;
	private JScrollPane jScrollPane1;
	protected ConfigFrame configFrame;
	protected AutoSSHConfigFrame autoSSHConfigFrame;
	protected ConfigTable configTable;
	protected About about;
	private MakeSource m;
	private JMenuItem miOpenDestCode;
	private JMenuItem miOpenDestBeans;
	private JSeparator separator;
	private JSeparator separator_1;
	private JMenuItem miDb2excel;
	private JSeparator separator_2;
	private JSeparator separator_3;
	private JMenuItem miExcel2Db;
	private JMenuItem miClearDestBeans;
	private JMenuItem miClearDestCode;
	private JSeparator separator_4;

	public Main() {
		menuBar = null;
		menuFile = null;
		menuEdit = null;
		menuHelp = null;
		miStart = null;
		miDoc = null;
		miCompileJava = null;
		miAutoSSH = null;
		miAutoConfig = null;
		miConfig = null;
		miSelectTable = null;
		miAbout = null;
		borderLayout = new BorderLayout();
		taInfo = new JTextArea();
		jScrollPane1 = new JScrollPane(taInfo);
		configFrame = null;
		autoSSHConfigFrame = null;
		configTable = null;
		about = null;
		m = null;
		getContentPane().setLayout(borderLayout);
		setDefaultCloseOperation(3);
		try {
			jbInit();
		} catch (Exception e) {
			Log.log(e);
			e.printStackTrace();
		}
		pack();
		GraphicsDevice device = GraphicsEnvironment
				.getLocalGraphicsEnvironment().getDefaultScreenDevice();
		DisplayMode d = device.getDisplayMode();
		int width = 800;
		int height = 520;
		setBounds((d.getWidth() - width) / 2, (d.getHeight() - height) / 2,
				800, 520);
		setVisible(true);
		// Log.log("欢迎使用AutoSSH代码生成工具,软件作者:李坤", 1000);
		// Log.log("更多内容欢迎访问我的博客: http://blog.csdn.net/lk_blog", 1000);
		Log.log("注:使用[编译实体类]功能需配置环境变量: JAVA_HOME", 5);
	}

	public static void main(String args[]) {
		new Main();
	}

	private void jbInit() throws Exception {
		setTitle("LKGenerator-" + AppConstants.APP_VERSION + " ");
		menuBar = new JMenuBar();
		menuBar.setMargin(new Insets(1, 1, 1, 1));
		menuBar.setFont(new Font("楷体", Font.PLAIN, 18));
		menuFile = new JMenu("数据表生成元数据");
		menuEdit = new JMenu("元数据生成代码");
		taInfo.setLineWrap(true);
		taInfo.setText(" 欢迎使用本代码生成工具,作者:天赋吉运 李坤 \n" +
				" 欢迎访问我的博客: http://blog.csdn.net/lk_blog \n" +
				" 源代码地址: http://git.oschina.net/likun5/lk-generator \n \n");
		taInfo.setRows(20);
		taInfo.setColumns(50);
		taInfo.setAutoscrolls(true);
		taInfo.setEnabled(true);
		taInfo.setFont(new Font("楷体", Font.PLAIN, 14));
		miStart = new JMenuItem("生成元数据代码");
		menuFile.setFont(new Font("楷体", Font.PLAIN, 18));
		menuEdit.setFont(new Font("楷体", Font.PLAIN, 18));
		miStart.setFont(new Font("楷体", Font.PLAIN, 16));
		menuBar.add(menuFile);
		menuBar.add(menuEdit);
		miAutoSSH = new JMenuItem("从元数据生成代码");
		miAutoConfig = new JMenuItem("配置");
		menuEdit.add(miAutoConfig);
		miAutoConfig.setFont(new Font("楷体", Font.PLAIN, 16));
		miAutoConfig.addActionListener(this);

		separator_2 = new JSeparator();
		menuEdit.add(separator_2);
		menuEdit.add(miAutoSSH);
		miAutoSSH.setFont(new Font("楷体", Font.PLAIN, 16));

		miOpenDestCode = new JMenuItem("打开目标代码目录");
		miOpenDestCode.setFont(new Font("楷体", Font.PLAIN, 16));
		miOpenDestCode.addActionListener(this);

		separator_4 = new JSeparator();
		menuEdit.add(separator_4);

		miClearDestCode = new JMenuItem("清空目标代码目录");
		miClearDestCode.setFont(new Font("楷体", Font.PLAIN, 16));
		menuEdit.add(miClearDestCode);
		miClearDestCode.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Config config = (new ConfigXmlUtil()).getConfig();
				FileUtil.delAllFile(config.getDestCodeDir());
				Log.log("清空目标代码目录成功！", 3);
			}
		});
		menuEdit.add(miOpenDestCode);
		miAutoSSH.addActionListener(this);
		menuHelp = new JMenu("\u5E2E\u52A9");
		miAbout = new JMenuItem("关于");
		miAbout.setFont(new Font("楷体", Font.PLAIN, 16));
		menuHelp.setFont(new Font("楷体", Font.PLAIN, 18));
		menuBar.add(menuHelp);
		menuHelp.add(miAbout);
		miAbout.addActionListener(this);
		miConfig = new JMenuItem("配置");
		menuFile.add(miConfig);
		miConfig.setFont(new Font("楷体", Font.PLAIN, 16));
		miConfig.addActionListener(this);
		miSelectTable = new JMenuItem("\u9009\u53D6\u8868");
		menuFile.add(miSelectTable);
		miSelectTable.setFont(new Font("楷体", Font.PLAIN, 16));
		miSelectTable.addActionListener(this);

		separator_1 = new JSeparator();
		menuFile.add(separator_1);
		menuFile.add(miStart);
		miStart.addActionListener(this);

		miCompileJava = new JMenuItem("编译元数据");
		miCompileJava.setFont(new Font("楷体", Font.PLAIN, 16));
		miCompileJava.addActionListener(this);
		menuFile.add(miCompileJava);

		separator_3 = new JSeparator();
		menuFile.add(separator_3);

		miDb2excel = new JMenuItem("导出数据到Excel");
		miDb2excel.setFont(new Font("楷体", Font.PLAIN, 16));
		menuFile.add(miDb2excel);

		miDoc = new JMenuItem("生成数据表文档");
		miDoc.setFont(new Font("楷体", Font.PLAIN, 16));
		miDoc.addActionListener(this);

		miExcel2Db = new JMenuItem("从Excel导入DB");
		miExcel2Db.setFont(new Font("楷体", Font.PLAIN, 16));
		miExcel2Db.addActionListener(this);
		menuFile.add(miExcel2Db);
		menuFile.add(miDoc);

		separator = new JSeparator();
		menuFile.add(separator);

		miClearDestBeans = new JMenuItem("清空元数据代码目录");
		miClearDestBeans.setFont(new Font("楷体", Font.PLAIN, 16));
		miClearDestBeans.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				FileUtil.delAllFile(TableConfig.getInstance().getPath());
				Log.log("清空元数据代码目录成功！", 3);
			}
		});
		menuFile.add(miClearDestBeans);

		miOpenDestBeans = new JMenuItem("打开元数据代码目录");
		miOpenDestBeans.setFont(new Font("楷体", Font.PLAIN, 16));
		menuFile.add(miOpenDestBeans);
		miOpenDestBeans.addActionListener(this);
		miDb2excel.addActionListener(this);

		getContentPane().add(menuBar, "First");
		getContentPane().add(jScrollPane1, "Center");
		TableConfig.getInstance().setLogArea(taInfo);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		ConfigXmlUtil config = new ConfigXmlUtil();
		if (event.getSource() == miOpenDestCode) {
			try {
				String destDir = config.getConfig().getDestCodeDir();
				FileUtil.mkdirs(destDir);// 如果不存在则创建文件夹.

				java.awt.Desktop.getDesktop().open(new File(destDir));
			} catch (IOException e) {
				Log.log(e);
				e.printStackTrace();
			}
		} else if (event.getSource() == miOpenDestBeans) {
			try {
				String destDir = TableConfig.getInstance().getPath();
				FileUtil.mkdirs(destDir);// 如果不存在则创建文件夹.

				java.awt.Desktop.getDesktop().open(new File(destDir));
			} catch (IOException e) {
				Log.log(e);
				e.printStackTrace();
			}
		} else if (event.getSource() == miConfig) {
			if (configFrame == null) {
				configFrame = new ConfigFrame(this);
			}
			configFrame.setBounds((int) (getBounds().getX() + 15D),
					(int) (getBounds().getY() + 80D), (int) getBounds()
							.getWidth(), (int) getBounds().getHeight());
			configFrame.pack();
			configFrame.setVisible(true);
		} else if (event.getSource() == miSelectTable) {
			if (configTable == null) {
				configTable = new ConfigTable(this);
			}
			configTable.setBounds((int) (getBounds().getX() + 120D),
					(int) (getBounds().getY() + 80D), (int) getBounds()
							.getWidth(), (int) getBounds().getHeight());
			configTable.pack();
			configTable.setVisible(true);
		} else if (event.getSource() == miStart) {
			run();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				Log.log(e);
				e.printStackTrace();
			}
			AutoMain.compileJava();
		} else if (event.getSource() == miDb2excel) {
			DBExcelDataUtil.db2Excel();
		} else if (event.getSource() == miExcel2Db) {
			DBExcelDataUtil.excel2Db();
		} else if (event.getSource() == miDoc) {
			MakeTableDoc mtd = new MakeTableDoc();
			mtd.start();
		} else if (event.getSource() == miCompileJava) {
			AutoMain.compileJava();
		} else if (event.getSource() == miAutoSSH) {
			AutoMain.run();
		} else if (event.getSource() == miAutoConfig) {
			if (autoSSHConfigFrame == null) {
				autoSSHConfigFrame = new AutoSSHConfigFrame(this);
			}
			autoSSHConfigFrame.setBounds((int) (getBounds().getX() + 12D),
					(int) (getBounds().getY() + 80D), (int) getBounds()
							.getWidth(), (int) getBounds().getHeight());
			autoSSHConfigFrame.pack();
			autoSSHConfigFrame.setVisible(true);
		} else if (event.getSource() == miAbout) {
			try {
				validateFolder(AppConstants.BASE_PATH + ".help",
						"/res/.help");
				String destDir = AppConstants.BASE_PATH + ".help";
				FileUtil.mkdirs(destDir);// 如果不存在则创建文件夹.
				java.awt.Desktop.getDesktop().open(new File(destDir));
			} catch (IOException e) {
				Log.log(e);
				e.printStackTrace();
			}
			if (about == null) {
				about = new About(this);
			}
			about.setBounds((int) (getBounds().getX() + 120D),
					(int) (getBounds().getY() + 80D), (int) getBounds()
							.getWidth(), (int) getBounds().getHeight());
			about.pack();
			about.setVisible(true);
		}
	}

	@Override
	public void run() {
		m = new MakeSource();
		m.start();
	}

	private void validateFolder(String filePath, String jarInPath) {
		filePath = FileUtil.filterDir(filePath);
		File file = new File(filePath);
		if (!file.exists()) {
			InputStream in = this.getClass().getResourceAsStream(
					"/filelist.txt");
			InputStreamReader reader;
			BufferedReader bufferedReader;
			String tempString = null;
			// 一次读入一行，直到读入null为文件结束
			if (in == null) {
				return;
			}
			try {
				reader = new InputStreamReader(in);
				bufferedReader = new BufferedReader(reader);
				while ((tempString = bufferedReader.readLine()) != null) {
					if (tempString.startsWith(jarInPath)) {
						FileUtil.copyFile(
								this.getClass().getResourceAsStream(
										 tempString),
								FileUtil.makeFilePath(filePath
										+ tempString.replace(jarInPath, "")));
					}
				}
				bufferedReader.close();
				reader.close();
			} catch (IOException e1) {
				Log.log(e1);
				e1.printStackTrace();
			}

		}
	}

}